from django.shortcuts import render, redirect  # render：生成并返回页面内容  redirect：重定向页面
from myApp.models import User
from django.core.paginator import Paginator
from .utils.error import *
from .utils import getHomeData, getSelfInfo
import hashlib
from .utils.getHomeData import getUserCreateTime
from .utils import getChangePasswordData
from .utils import getHistoryData
from .utils.error import *
from .utils import getTableData
from .utils import getSalaryCharData
from .utils import getCompanyCharData
from .utils import getEducationalCharData
from .utils import getCompanyStatusCharData
from .utils import getAddressCharData
from myApp import word_cloud_picture
import random


# Create your views here.
def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    else:
        uname = request.POST.get('username')
        pwd = request.POST.get('password')
        md5 = hashlib.md5()
        md5.update(pwd.encode())
        pwd = md5.hexdigest()
        try:
            user = User.objects.get(username=uname, password=pwd)  # 获取用户信息
            request.session['username'] = uname  # 登录成功，设置会话
            return redirect('/myApp/home')  # 重定向到主页
        except:
            return errorResponse(request, '用户名或密码错误')  # 捕获异常，用户名或密码错误


def register(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    else:
        uname = request.POST.get('username')
        pwd = request.POST.get('password')
        checkPwd = request.POST.get('checkPassword')
        try:
            User.objects.get(username=uname)  # 在数据库内查找是否有相同用户名的用户
        except:
            if not uname or not pwd or not checkPwd: return errorResponse(request, '不允许为空')  # 必填项检查
            if pwd != checkPwd: return errorResponse(request, '两次密码不符合')  # 密码检查
            md5 = hashlib.md5()
            md5.update(pwd.encode())
            pwd = md5.hexdigest()
            User.objects.create(username=uname, password=pwd)  # 在User表中新增用户信息
            return redirect('/myApp/login')  # 注册成功后跳转到登录页面
        return errorResponse(request, '该用户名已注册！')  # 如果用户名已存在，返回错误


def logOut(request):
    request.session.clear()
    return redirect('login')  # redirect可以写路由名字


def home(request):
    # 用户名
    uname = request.session.get('username')
    # 用户信息
    userInfo = User.objects.get(username=uname)
    # 当前时间
    year, month, day = getHomeData.getNowTime()
    # 右侧标签
    jobsLen, usersLen, educationsTop, salaryTop, salaryMonthTop, addressTop, practiceMax = getHomeData.getTagData()
    # 用户创建时间
    userTime = getUserCreateTime()
    # 最新创建的5个用户信息
    newUser = getHomeData.getUserTop5()
    # 数据爬取时间
    allJobsPBar = getHomeData.getAllJobsPBar()
    # 数据表格
    tableData = getHomeData.getTableData()
    return render(request, 'index.html', {
        'username': uname,
        'userAvatar': userInfo.avatar,
        'year': year,
        "month": month,
        'day': day,
        'jobsLen': jobsLen,
        'usersLen': usersLen,
        'educationsTop': educationsTop,
        'salaryTop': salaryTop,
        'salaryMonthTop': salaryMonthTop,
        'practiceMax': practiceMax,
        'addressTop': addressTop,
        'userTime': userTime,
        'newUser': newUser,
        'allJobsPBar': allJobsPBar,
        'tableData': tableData
    })


def selfInfo(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    educations, workExperience, jobList = getSelfInfo.getPageData()
    if request.method == "POST":
        getSelfInfo.changeSelfInfo(request.POST, request.FILES)  # 修改用户信息
        userInfo = User.objects.get(username=uname)  # 更新用户信息
    return render(request, 'selfInfo.html', {
        'userInfo': userInfo,
        'pageData': {
            'educations': educations,
            'workExperience': workExperience,
            'jobList': jobList
        }
    })


def changePassword(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    if request.method == "POST":
        res = getChangePasswordData.changePasswordData(userInfo, request.POST)
        if res != None:
            return errorResponse(request, res)
        userInfo = User.objects.get(username=uname)

    return render(request, 'changePassword.html', {
        'userInfo': userInfo,
    })


def tableData(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    tableData = getTableData.getTableData()
    paginator = Paginator(tableData, 10)
    cur_page = 1
    if request.GET.get('page'): cur_page = int(request.GET.get('page'))
    if cur_page:
        c_page = paginator.page(cur_page)
    else:
        c_page = paginator.page(1)

    page_range = []
    visibleNumber = 10
    min = int(cur_page - visibleNumber / 2)
    if min < 1:
        min = 1
    max = min + visibleNumber
    if max > paginator.page_range[-1]:
        max = paginator.page_range[-1]
    for i in range(min, max):
        page_range.append(i)

    return render(request, 'tableData.html', {
        'userInfo': userInfo,
        'c_page': c_page,
        'page_range': page_range,
        'paginator': paginator
    })


def historyTableData(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    historyData = getHistoryData.getHistoryData(userInfo)
    return render(request, 'historyTableData.html', {
        'userInfo': userInfo,
        'historyData': historyData
    })


def addHistory(request, jobId):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    getHistoryData.addHistory(userInfo, jobId)
    return redirect('historyTableData')


def removeHistory(request, hisId):
    getHistoryData.removeHistory(hisId)
    return redirect('historyTableData')

def salary(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    educations,workExperiences = getSalaryCharData.getPageData()
    defaultEducation = '不限'
    defaultWorkExperience = '不限'
    if request.GET.get('educational'):
        defaultEducation = request.GET.get('educational')
    if request.GET.get('workExperience'):
        defaultWorkExperience = request.GET.get('workExperience')
    salaryList, barData, legends = getSalaryCharData.getBarData(defaultEducation,defaultWorkExperience)
    pieData = getSalaryCharData.pieData()
    louDouData = getSalaryCharData.getLoudouData()
    return render(request,'salaryChart.html',{
        'userInfo': userInfo,
        'educations': educations,
        'workExperiences': workExperiences,
        'defaultEducation': defaultEducation,
        'defaultWorkExperience': defaultWorkExperience,
        'salaryList': salaryList,
        'barData': barData,
        'legends': legends,
        'pieData': pieData,
        'loudouData': louDouData
    })

def company(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    typeList = getCompanyCharData.getPageData()
    type = 'all'
    if request.GET.get('type'):
        type = request.GET.get('type')
    rowBarData,columnBarData = getCompanyCharData.getCompanyBar(type)
    pieData = getCompanyCharData.getCompanyPie(type)
    companyPeople,lineData = getCompanyCharData.getCompanyPeople(type)
    return render(request, 'companyChar.html', {
        'userInfo': userInfo,
        'typeList': typeList,
        'type': type,
        'rowBarData': rowBarData,
        'columnBarData': columnBarData,
        'pieData':pieData,
        'companyPeople':companyPeople,
        'lineData':lineData
    })

def companyTags(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    return render(request, 'companyTags.html', {
        'userInfo': userInfo,
    })

def educational(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)

    educations = getEducationalCharData.getPageData()
    defaultEducation = '不限'

    if request.GET.get('educational'): defaultEducation = request.GET.get('educational')

    workExperiences,charDataColumnOne,charDataColumnTwo,hasEmpty = getEducationalCharData.getExperienceData(defaultEducation)

    barDataRow,barDataColumn = getEducationalCharData.getPeopleData()

    return render(request, 'educationalChar.html', {
        'userInfo': userInfo,
        'educations': educations,
        'defaultEducation': defaultEducation,
        'workExperiences': workExperiences,
        'charDataColumnOne': charDataColumnOne,
        'charDataColumnTwo': charDataColumnTwo,
        'hasEmpty': hasEmpty,
        'barDataRow': barDataRow,
        'barDataColumn': barDataColumn
    })

def companyStatus(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    typeList = getCompanyStatusCharData.getPageData()
    defaultType = '不限'
    if request.GET.get('type'): defaultType = request.GET.get('type')
    technologyRow, technologyColumn = getCompanyStatusCharData.getTechnologyData(defaultType)
    companyStatusData = getCompanyStatusCharData.getCompanyStatusData()
    return render(request, 'companyStatusChar.html', {
        'userInfo': userInfo,
        'typeList': typeList,
        'defaultType': defaultType,
        'technologyRow': technologyRow,
        'technologyColumn': technologyColumn,
        'companyStatusData': companyStatusData
    })

def address(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    hotCities = getAddressCharData.getPageData()
    defaultCity = '北京'
    if request.GET.get('city'):defaultCity = request.GET.get('city')  # GET获取字典,get获取值
    salaryRows, salaryColumn = getAddressCharData.getSalaryData(defaultCity)
    companyPeople = getAddressCharData.getCompanyPeopleData(defaultCity)
    educationData = getAddressCharData.getEducationData(defaultCity)
    distData = getAddressCharData.getDist(defaultCity)
    randomPicture = random.randint(1,1000000)
    word_cloud_picture.get_img('companyTags','./static/2.jpg','./static/'+str(randomPicture)+'.png')
    return render(request, 'addressChar.html', {
        'userInfo': userInfo,
        'hotCities': hotCities,
        'defaultCity': defaultCity,
        'salaryRows': salaryRows,
        'salaryColumn': salaryColumn,
        'companyPeople': companyPeople,
        'educationData': educationData,
        'distData': distData,
        'url':randomPicture
    })